import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { Variants } from 'framer-motion';
import axios from 'axios';
import BackButton from '../components/BackButton';

interface FESResponse {
  trans_code: string;
  bank_date: string;
  resp_code: string;
  orderid: string;
  org_orderid: string;
  org_trans_sn: string;
  org_resp_code: string;
  org_rrn: string;
  pan: string;
  error_msg?: string;
}

const FES: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<FESResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [payOrder, setPayOrder] = useState('');

  // 动画配置
  const containerVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.6,
        ease: [0.43, 0.13, 0.23, 0.96]
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!payOrder.trim()) {
      setError('请输入外部订单号');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const now = new Date();
      const requestData = {
        trans_code: "FES",
        appid: "01",
        orderid: `FES${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`,
        trans_date: `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`,
        trans_time: `${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`,
        org_trans_code: "CEP",
        org_pay_order: payOrder.trim(),
        merno: "999999999999997",
        terminal: "99999996"
      };

      console.log('发送请求数据:', requestData);
      
      const response = await axios.post('/api/fes', requestData);
      console.log('收到响应:', response.data);
      
      if (response.data.resp_code !== '0') {
        setError(response.data.error_msg || '查询失败');
      } else {
        setResult(response.data);
      }
    } catch (err: any) {
      console.error('请求错误:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error_msg || '查询失败，请稍后重试';
      setError(typeof errorMessage === 'string' ? errorMessage : '查询失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const getStatusText = (code: string): string => {
    const statusMap: { [key: string]: string } = {
      '0': '成功',
      '1': '失败',
      '2': '处理中',
      '3': '未知'
    };
    return statusMap[code] || `未知(${code})`;
  };

  const getStatusColor = (code: string): string => {
    const colorMap: { [key: string]: string } = {
      '0': 'bg-green-100 text-green-800',
      '1': 'bg-red-100 text-red-800',
      '2': 'bg-yellow-100 text-yellow-800',
      '3': 'bg-gray-100 text-gray-800'
    };
    return colorMap[code] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#eaf2ff] via-[#f0f7ff] to-[#f8fbff] py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
      <BackButton />
      
      {/* 背景装饰 */}
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob"></div>
        <div className="absolute -bottom-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-2000"></div>
      </div>

      <motion.div
        className="max-w-4xl mx-auto"
        initial="hidden"
        animate="visible"
        variants={containerVariants}
      >
        <div className="text-center mb-10">
          <h1 className="text-4xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-500">
            交易状态查询
          </h1>
          <p className="mt-3 text-xl text-gray-600">
            查询消费或退货交易的处理状态
          </p>
        </div>

        <div className="bg-white/60 backdrop-blur-xl rounded-2xl p-8 shadow-[0_8px_32px_rgba(0,0,0,0.08)] border border-white/30">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="payOrder" className="block text-sm font-medium text-gray-700 mb-2">
                外部订单号
              </label>
              <input
                type="text"
                id="payOrder"
                value={payOrder}
                onChange={(e) => setPayOrder(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-white/50 border border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200 outline-none"
                placeholder="请输入要查询的外部订单号"
              />
            </div>

            <div>
              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 px-6 bg-indigo-500 text-white rounded-xl hover:bg-indigo-600 transition-colors duration-200 disabled:opacity-50"
              >
                {loading ? '查询中...' : '查询'}
              </button>
            </div>

            {error && (
              <div className="p-4 rounded-xl bg-red-50 text-red-700 text-sm">
                {error}
              </div>
            )}

            <AnimatePresence>
              {result && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="mt-8 space-y-4 bg-white/80 rounded-xl p-6"
                >
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-4">原交易信息</h3>
                      <div className="space-y-4">
                        <div>
                          <p className="text-sm text-gray-500">卡号</p>
                          <p className="text-base font-medium text-gray-900 font-mono">
                            {result.pan}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">原交易流水号</p>
                          <p className="text-base font-medium text-gray-900 font-mono">
                            {result.org_trans_sn}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">原交易订单号</p>
                          <p className="text-base font-medium text-gray-900 font-mono">
                            {result.org_orderid}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">原交易状态</p>
                          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(result.org_resp_code)}`}>
                            {getStatusText(result.org_resp_code)}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div>
                      <h3 className="text-lg font-medium text-gray-900 mb-4">查询信息</h3>
                      <div className="space-y-4">
                        <div>
                          <p className="text-sm text-gray-500">查询流水号</p>
                          <p className="text-base font-medium text-gray-900 font-mono">
                            {result.orderid}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">清算日期</p>
                          <p className="text-base font-medium text-gray-900">
                            {`${result.bank_date.slice(0, 4)}-${result.bank_date.slice(4, 6)}-${result.bank_date.slice(6, 8)}`}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">查询状态</p>
                          <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(result.resp_code)}`}>
                            {getStatusText(result.resp_code)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </form>
        </div>
      </motion.div>
    </div>
  );
};

export default FES; 